<?php
namespace HC\Swoole;

function sw_class_exists(string $class)
{
    if (!class_exists($class)) {
        throw new \InvalidArgumentException($class . ' is not exists');
    }
}

function sw_json_encode($value, $options = 0, $depth = 512)
{
    $value = json_encode($value, $options, $depth);

    if ($value === false && json_last_error() !== JSON_ERROR_NONE) {
        throw new \UnexpectedValueException(json_last_error_msg(), json_last_error());
    }

    return $value;
}

function sw_json_decode($json, $assoc = true, $depth = 512, $options = 0)
{
    $value = json_decode($json, $assoc, $depth, $options);

    if ($value === null && json_last_error() !== JSON_ERROR_NONE) {
        throw new \UnexpectedValueException(json_last_error_msg(), json_last_error());
    }

    return $value;
}

function normalizeArray(array $data) : array
{
    foreach ($data as $key => $value) {
        if (is_object($value)) {
            throw new \UnexpectedValueException('array invalid object value');
        }

        if (is_array($value)) {
            $value = normalizeArray($value);
        } else {
            if (is_bool($value)) {
                $value = (int) $value;
            }

            $value = (string) $value;
        }

        $data[$key] = $value;
    }

    return $data;
}